package com.ruoyi.web.controller.common;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.mongodb.FileModel;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.service.FileService;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @version v1.0
 * @ProjectName: ruoyi-vue-plus
 * @ClassName: FileController
 * @Description: TODO(文件接口)
 * @Author: Yanghaha
 * @Date: 2021/5/14 11:40
 */
@RestController
@RequestMapping("/files")
public class FileController {
    @Autowired
    private FileService fileService;

    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private String serverPort;

//    @RequestMapping(value = "/")
//    public String index(Model model) {
//        // 展示最新二十条数据
//        model.addAttribute("files", fileService.listFilesByPage(0, 20));
//        return "index";
//    }

    /**
     * 分页查询文件
     */
    @GetMapping("files/{pageIndex}/{pageSize}")
    @ResponseBody
    public List<FileModel> listFilesByPage(@PathVariable int pageIndex, @PathVariable int pageSize) {
        return fileService.listFilesByPage(pageIndex, pageSize);
    }

    /**
     * 获取文件片信息
     */
    @GetMapping("/serveFile")
    @ResponseBody
    public ResponseEntity<Object> serveFile(@RequestParam("id") String id) throws UnsupportedEncodingException {

        Optional<FileModel> file = fileService.getFileById(id);

        if (file.isPresent()) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=" + new String(file.get().getName().getBytes("utf-8"),"ISO-8859-1"))
                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                    .header(HttpHeaders.CONTENT_LENGTH, file.get().getSize() + "").header("Connection", "close")
                    .body(file.get().getContent().getData());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }

    }

    /**
     * 在线显示文件
     */
    @GetMapping("/view")
    @ResponseBody
    public ResponseEntity<Object> serveFileOnline(@RequestParam("id") String id) {

        Optional<FileModel> file = fileService.getFileById(id);

        if (file.isPresent()) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + file.get().getName() + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, file.get().getContentType())
                    .header(HttpHeaders.CONTENT_LENGTH, file.get().getSize() + "").header("Connection", "close")
                    .body(file.get().getContent().getData());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }

    }



    /**
     * 上传接口
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult handleFileUpload(@RequestParam("files") MultipartFile[] files) {
        List<String> ids=new ArrayList<>();
        List<String> fileNameList=new ArrayList<>();
        try{
            for (MultipartFile img : files) {
                if (img.getSize() > 0) {
                    // 上传文件
                    FileModel fileModel = fileService.saveFile(img);
                    ids.add(fileModel.getId());
                    fileNameList.add(fileModel.getName());
                }
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("ids", ids);
            ajax.put("fileNameList", fileNameList);
            return ajax;
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("上传图片异常，请联系管理员");
        }


//        if (!file.isEmpty()) {
//            // 上传文件
//            FileModel fileModel = fileService.saveFile(file);
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("url", fileModel.getPath());
//            return ajax;
//        }
    }

    /**
     * 删除文件
     */
    @GetMapping("/delete")
    @ResponseBody
    public ResponseEntity<String> deleteFile(@RequestParam("id") String id) {

        try {
            fileService.removeFile(id);
            return ResponseEntity.status(HttpStatus.OK).body("DELETE Success!");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
}
